import editForm from "../form.vue";
import { message } from "@/utils/message";
import { getDictList, addDict, editDict, resetDict, delDict } from "@/api/data";
import { ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import { deviceDetection } from "@pureadmin/utils";
import { reactive, ref, onMounted, toRaw, h } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { Result } from "@/utils/http/utils";
import { usePublicHooks } from "@/views/hooks";

export function useRole() {
  const form = reactive({
    page: 1,
    pageSize: 10,
    name: "",
    code: "",
    status: ""
  });
  const formRef = ref();
  const drawer = ref(false);
  const switchLoadMap = ref({});
  const dataList = ref([]);
  const loading = ref(true);
  const { switchStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      prop: "id",
      minWidth: 60
    },
    {
      label: "字典名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "字典标识",
      prop: "code",
      minWidth: 80
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 120
    },
    {
      label: "操作",
      fixed: "right",
      width: 230,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        resetDict({ id: row.id, status: row.status })
          .then((result: Result) => {
            if (result && result.code == 200) {
              message(result.message, { type: "success" });
              onSearch();
            }
          })
          .catch(error => {
            console.error("请求失败:", error);
          });

        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );

        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
        }, 300);
      })
      .catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}数据`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          name: row?.name ?? "",
          code: row?.code ?? "",
          status: row?.status ?? 1,
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              addDict(curData)
                .then((result: Result) => {
                  if (result && result.code == 200) {
                    message("操作成功", { type: "success" });
                    chores();
                  }
                })
                .catch(error => {
                  console.error("请求失败:", error);
                });
            } else {
              editDict(curData)
                .then((result: Result) => {
                  if (result && result.code == 200) {
                    message("操作成功", { type: "success" });
                    chores();
                  }
                })
                .catch(error => {
                  console.error("请求失败:", error);
                });
            }
          }
        });
      }
    });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    delDict({ id: row.id })
      .then((result: Result) => {
        if (result && result.code == 200) {
          message("操作成功", { type: "success" });
          onSearch();
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
      });
  }

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getDictList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    drawer,
    pagination,
    onSearch,
    openDialog,
    resetForm,
    handleCurrentChange,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleSelectionChange
  };
}
